package Handlers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogHandler extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
//	private int logTimeOut = 5000;
	private boolean logDebugOn = false;
	

	public boolean isLogDebugOn() {
		return logDebugOn;
	}

	public void setLogDebugOn(boolean logDebugOn) {
		this.logDebugOn = logDebugOn;
	}

//	public int getLogTimeOut() {
//		return logTimeOut;
//	}
//
//	public void setLogTimeOut(int logTimeOut) {
//		this.logTimeOut = logTimeOut;
//	}
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {   
		processRequest(req, resp);
    }
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		    processRequest(req, resp);
	}
	
	private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		final String timeout = req.getParameter("log_observer_timeout");
//		if(timeout != null && !timeout.isEmpty())
//		{
//			setLogTimeOut(Integer.parseInt(timeout));
//		}
//		
		String debug = req.getParameter("debug");
		if(debug != null && !debug.isEmpty())
		{
			setLogDebugOn(Boolean.valueOf(debug));
		}
		
		final StringBuilder result = new StringBuilder();//MUST be mutable object
		if(isLogDebugOn())
		{
			result.append( LogObserver.ApplicationInitialiser.getInstance().Scan());
//			new Thread(new Runnable() {
//				
//				@Override
//				public void run() {
//					try {
//						result.append(LogObserver.ApplicationInitialiser.getInstance().Scan());
//						try {
//							Thread.sleep(Long.valueOf(timeout));
//						} catch (NumberFormatException e) {
//							e.printStackTrace();
//						} catch (InterruptedException e) {
//							e.printStackTrace();
//						}
//					} catch (FileNotFoundException e) {
//						e.printStackTrace();
//					}
//				}
//			}); 
		}
		resp.setContentType("text/plain; charset=utf-8");
	    PrintWriter pw = resp.getWriter();
	    pw.println(result);
	}
	
}
